import React, { useState } from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';

function Copyright() {
  return (
    <Typography variant="body2" color="textSecondary" align="center">
      {'Copyright © '}
      <Link color="inherit" href="https://github.com/nullptrjzz">
        nullptrjzz
      </Link>{' '}
      {new Date().getFullYear()}
      {'.'}
    </Typography>
  );
}

const useStyles = makeStyles((theme) => ({
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main,
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(1),
  },
  submit: {
    margin: theme.spacing(3, 0, 2),
  },
  img: {
    margin: 'auto',
    display: 'block',
    maxWidth: '100%',
    maxHeight: '100%',
  },
}));

let smsWaitingSecond = -1

export default function SignIn() {
  const classes = useStyles();
  const inputCaptchaType = ['text', 'calc', 'sms'];
  const type = document.getElementById('type').innerHTML;
  localStorage.setItem('type', type);

  let smsCd = undefined

  const [smsWaiting, setSmsWaiting] = useState(-1)
  const [url, setUrl] = useState('/api/' + type + '/code?t=' + Date.now());

  const isInputCaptcha = inputCaptchaType.indexOf(type) > -1;

  const formTextBody = (
    <>
      <TextField
        variant="outlined"
        margin="normal"
        required
        fullWidth={true}
        id="username"
        label="用户名"
        name="username"
        autoComplete="username"
        autoFocus
      />
      <TextField
        variant="outlined"
        margin="normal"
        required
        fullWidth={true}
        name="password"
        label="密码"
        type="password"
        id="password"
        autoComplete="current-password"
      />
    </>
  );

  const showCaptchaPopup = () => {
    const cmd = 'captchaInit(() => { document.getElementById("login-form").submit() }, "' + type + '")'
    eval(cmd)
  }

  const startSmsCountDown = (timeout=60) => {
    stopSmsCountDown()
    setSmsWaiting(timeout)
    smsWaitingSecond = timeout
    
    smsCd = setInterval(() => {
      setSmsWaiting(smsWaitingSecond - 1)
      smsWaitingSecond--;
      if (smsWaitingSecond <= 0) {
        stopSmsCountDown()
      }
    }, 1000)
  }

  const stopSmsCountDown = () => {
    if (smsCd !== undefined) {
      clearInterval(smsCd)
    }
    setSmsWaiting(-1)
  }

  const fetchSms = () => {
    const phone = document.getElementById('phone').value
    if (phone.trim() === '' || phone.length < 11) {
      alert('请输入有效的手机号码')
      return
    }

    startSmsCountDown()
    fetch('/api/sms/code', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: 'phone=' + phone,
      credentials: 'include',
      mode: 'cors'
    }).then(res => {
      if (res.status >= 400) {
        stopSmsCountDown()
      }
      return res
    }).then(resp => {
      return resp.json()
    }).then(resp => {
      try {
        if (resp['code'] === -1) {
          const reg = new RegExp('(.)+[0-9]+秒(.)+')
          if (reg.test(resp['message'])) {
            const splitReg = new RegExp('[0-9]+秒')
            var timeout = parseInt(splitReg.exec(resp['message'])[0].replace('秒', ''))
            startSmsCountDown(timeout)
          } else {
            startSmsCountDown()
          }
          alert(resp['message'])
        } else if (resp['Response']['SendStatusSet'][0]['Code'] === 'Ok') {
          // Send success
        } else {
          alert(resp['Response']['SendStatusSet'][0]['Message'])
          stopSmsCountDown()
        }
      } catch(e) {
        alert(e)
        stopSmsCountDown()
      }
    })
  }

  const reloadCaptcha = () => {
    setUrl('/api/' + type + '/code?t=' + Date.now())
  }

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          登录
        </Typography>
        <form id="login-form" className={classes.form} action={'/api/' + type + '/login'} method="post" encType="application/x-www-form-urlencoded" noValidate>
          {
            isInputCaptcha ? (
              <>
                {formTextBody}
                {type === 'sms' && (
                  <>
                    <TextField
                      variant="outlined"
                      margin="normal"
                      required
                      fullWidth={true}
                      id="phone"
                      label="手机号码"
                      name="phone"
                      autoComplete="phone"
                      type="tel"
                    />
                  </>
                )}
                <Grid container spacing={3}>
                  <Grid item xs={5} sm={type === 'sms' ? 5 : 6} md={type === 'sms' ? 6 : 7}>
                    <TextField
                      variant="outlined"
                      margin="normal"
                      required
                      fullWidth={true}
                      name="_v"
                      label="验证码"
                      type="text"
                      id="_v"
                    />
                  </Grid>
                  <Grid item xs={7} sm={type === 'sms' ? 7 : 6} md={type === 'sms' ? 6 : 5}>
                    {type === 'sms' ? (
                      <>
                        <div style={{ height: '100%', display: 'flex', alignItems: 'center' }}>
                          <Button
                            type="button"
                            fullWidth={true}
                            variant="contained"
                            color="secondary"
                            disabled={smsWaiting >= 0}
                            style={{ width: '100%', padding: '8px' }}
                            onClick={fetchSms}
                          >
                            {smsWaiting >= 0 ? '验证码已发送 (' + smsWaiting + 's)' : '获取验证码'}
                          </Button>
                        </div>
                      </>
                    ) : (
                      <>
                        <div style={{ display: 'flex', height: '100%', alignItems: 'center', cursor: 'pointer' }} onClick={() => reloadCaptcha()}>
                          <img className={classes.img} alt="验证码" src={url} />
                        </div>
                      </>
                    )}
                  </Grid>
                </Grid>
                <Button
                  type="submit"
                  fullWidth={true}
                  variant="contained"
                  color="primary"
                  className={classes.submit}
                >
                  登录
              </Button>
                <Grid container>
                  <Grid item xs>
                    <Link href="/" variant="body2">
                      返回首页
                  </Link>
                  </Grid>
                </Grid>
              </>
            ) : (<>
              {formTextBody}
              <Button
                type="button"
                fullWidth={true}
                variant="contained"
                color="primary"
                className={classes.submit}
                onClick={showCaptchaPopup}
              >
                登录
              </Button>
              <Grid container>
                <Grid item xs>
                  <Link href="/" variant="body2">
                    返回首页
                  </Link>
                </Grid>
              </Grid>
            </>)
          }
        </form>
      </div>
      <Box mt={8}>
        <Copyright />
      </Box>
    </Container>
  );
}